<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="角色管理" name="role">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="clickShowAdd"
            >
              新增角色
            </el-button>
            <!-- border 边框 stripe斑马纹 -->
            <!-- 表单 -->
            <el-table
              v-loading="loading"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              :data="tableData"
              style="width: 100%"
              border
              stripe
            >
              <el-table-column
                type="index"
                label="序号"
                width="180"
                :index="indexMethod"
              />
              <el-table-column prop="name" label="角色名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="id" label="操作">
                <template #default="{row}">
                  <el-button
                    size="small"
                    type="success"
                    @click="clickShowAssignDialog(row.id)"
                  >
                    分配权限
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="updateRole(row.id)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- current-page  当前的页码数
          page-sizes 下拉选择框 范围
          page-size 每页条数
          layout 布局 total, sizes, prev, pager, next, jumper
          total 总条数
          @size-change ="处理函数" 每页条数发生修改的时候会触发
          @current-change ="处理函数"  页码发生变化的时候会触发 -->
            <!-- 分页器 -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 4, 8]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <!-- 新增编辑弹出层 -->
            <el-dialog
              :title="title"
              :visible="showRoleDialog"
              @close="btnCancel"
            >
              <el-form
                ref="roleForm"
                :model="form"
                :rules="rules"
                label-width="100px"
              >
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input
                    v-model="form.description"
                    placeholder="请输入角色描述"
                  />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="btnCancel">取消</el-button>
                <el-button type="primary" @click="btnAddRole">确认</el-button>
              </template>
            </el-dialog>
            <!-- 权限弹出层 -->
            <el-dialog
              title="分配权限"
              :visible="showAssignDialog"
              @close="closeAssignDialog"
              @open="openAssignDialog"
            >
              <!-- 内容部分 -->
              <!-- show-checkbox 展示复选框
           check-strictly 不遵循父子关联关系
           node-key="id" 获取和设置选中节点 必须设置node-key
           -->
              <el-tree
                ref="tree"
                v-loading="treeLoading"
                :data="permissionData"
                show-checkbox
                node-key="id"
                :default-expand-all="true"
                :props="{ label: 'name' }"
                check-strictly
              />
              <template #footer>
                <div style="text-align: right;">
                  <el-button @click="closeAssignDialog">取消</el-button>
                  <el-button type="primary" @click="clickAssign">
                    确定
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- alert警告 用于页面中展示重要的提示信息 -->
            <!-- :closable 是否可关闭 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyForm.name"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyForm.mailbox"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  addRoleApi,
  assignPermApi,
  delRoleApi,
  getRoleDetailApi,
  getRoleListApi,
  updateRoleApi
} from '@/api/setting'
import { getCompanyByIdApi } from '@/api/company'
import { mapState } from 'vuex'
import { getPermissionListApi } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Settings',
  data() {
    const nameVerify = (rule, value, callback) => {
      if (this.form.id && value === this.form.name) {
        return callback()
      }
      if (this.tableData.some(item => item.name === value)) {
        callback(new Error(`${value}角色信息已存在`))
      } else {
        callback()
      }
    }
    return {
      activeName: 'role', // 标签页的name属性
      tableData: [], // 角色渲染数据
      page: 1, // 页码
      pagesize: 4, // 页数,
      total: 0, // 数据总数,
      loading: false,
      showRoleDialog: false, // 新增角色的弹出层
      showAssignDialog: false, // 分配权限的弹出层
      roleId: '', // 分配权限时，记录正在操作的角色
      permissionData: [], // 权限数据
      treeLoading: false,
      title: '',
      form: {
        name: '',
        description: ''
      },
      companyForm: {},
      rules: {
        name: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: ['blur', 'change']
          },
          { validator: nameVerify, trigger: ['blur', 'change'] }
        ],
        description: [
          {
            required: true,
            message: '请输入角色描绘信息',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  created() {
    this.getRoleList()
    // this.getCompanyById()
  },
  methods: {
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 参数1是对应的面板组件, 参数2是事件对象
    handleClick(tab, event) {
      // console.log(tab, event)
      if (tab.name === 'company') {
        if (this.companyForm.name) return
        this.getCompanyById()
      }
    },
    async getRoleList() {
      this.loading = true
      const {
        data: {
          data: { rows, total }
        }
      } = await getRoleListApi(this.page, this.pagesize)
      this.total = total
      this.tableData = rows
      this.loading = false
    },
    // 每页条数发生修改的时候会触发，参数中是最新的每页条数
    handleSizeChange(newVal) {
      this.pagesize = newVal
      this.page = 1
      this.getRoleList()
    },
    // 页码发生变化的时候会触发,参数是最新的页码(自带实参)
    handleCurrentChange(newVal) {
      this.page = newVal
      this.getRoleList()
    },
    // 删除
    delRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          const { data } = await delRoleApi(id)
          this.$message.success(data.message)
          if (this.tableData.length === 1 && this.page > 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑
    async updateRole(id) {
      this.title = '编辑角色'
      this.showRoleDialog = true
      const {
        data: { data }
      } = await getRoleDetailApi(id)
      // console.log(data)
      this.form = data
    },
    clickShowAdd() {
      this.showRoleDialog = true
      this.title = '新增角色'
    },
    btnCancel() {
      this.showRoleDialog = false
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // 增加角色
    btnAddRole() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          // 编辑
          await updateRoleApi(this.form)
        } else {
          // 新建
          await addRoleApi(this.form)
        }
        // 关闭弹框
        this.showRoleDialog = false
        // 重新渲染
        this.getRoleList()
        // 添加成功
        this.$message.success('添加成功')
      })
    },
    // 根据id查询企业
    async getCompanyById() {
      const {
        data: { data }
      } = await getCompanyByIdApi(this.userInfo.companyId)
      // console.log(data)
      this.companyForm = data
    },
    // 分配角色的打开弹出层
    clickShowAssignDialog(id) {
      this.showAssignDialog = true
      this.roleId = id
    },
    // 关闭分配角色的打开弹出层
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    // 打开分配权限弹框时触发的事件
    async openAssignDialog() {
      this.treeLoading = true
      const {
        data: { data }
      } = await getPermissionListApi()
      this.permissionData = tranListToTreeData(data, '0')
      // console.log(this.permissionData)
      const {
        data: {
          data: { permIds }
        }
      } = await getRoleDetailApi(this.roleId)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
      this.treeLoading = false
    },
    // 确定分配权限
    async clickAssign() {
      const {
        data: { message }
      } = await assignPermApi({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success(message)
      this.showAssignDialog = false
    }
  }
}
</script>

<style></style>
